﻿from django import forms
from django.contrib.auth.models import User
from django.forms.formsets import DELETION_FIELD_NAME
from django.forms.models import inlineformset_factory
from yazasport.userprofile.models import UserProfile, Place
from yazasport.geography.models import L0Object, L1Object, L2Object, L34Object

# 75% TODO: Разделить форму редактирования профиля на несколько
# --- 10% TODO: Захуярить UserProfilePlaceForm(modelform) и UserProfilePlaceFormSet(frameset)
DATE_INPUT_FORMATS = ['%d/%m/%Y','%d.%m.%Y','%d/%m/%y','%d.%m.%y',]

class UserCreationForm(forms.ModelForm):
	
	
    username = forms.RegexField(label=u'Имя пользователя', max_length=30, regex=r'^\w+$',
        help_text = u"Обязательное поле. Не более 30. Принимаются цифры, буквы и знак подчеркивания.",
        error_message = u"Это поле должно содержать только цифры, буквы или знак подчеркивания.")
    password1 = forms.CharField(label=u"Пароль", widget=forms.PasswordInput)
    password2 = forms.CharField(label=u"Подтверждение пароля", widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email")

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(u"Пользователь с таким именем уже существует.")

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(u"Введенные пароли не совпадают.")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user
        
    
class UserProfileMainForm(forms.ModelForm):
	
	
    birth_date = forms.DateField(label=u'Дата рождения', required=False, input_formats=DATE_INPUT_FORMATS, widget=forms.DateInput(attrs = {'class': 'DatePicker'}))
        
    class Meta:
        model = UserProfile
        fields = ('first_name', 'last_name', 'gender', 'birth_date', 'marital_status', 'political_views', 'religious_views')

class UserProfileContactsForm(forms.ModelForm):
	
	
    contact_L34Object = forms.CharField(label=u'Город/поселок/деревня', required=False, widget=forms.TextInput(attrs={'autocomplete': 'off', 'class': 'id_L34Object'}))
    L34Object_hidden = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'autocomplete': 'off', 'class': 'id_L34Object_h'}))
      
    def __init__(self, *args, **kwargs):
        super(UserProfileContactsForm, self).__init__(*args, **kwargs)
        if self.instance:
            l34_name = self.instance.contact_L34Object.name if self.instance.contact_L34Object is not None else ''
            l34 = str(self.instance.contact_L34Object.id) if self.instance.contact_L34Object is not None else '0'
            l2 = str(self.instance.contact_L2Object.id) if not self.instance.contact_L2Object in [None, 0] else '0'
            l1 = str(self.instance.contact_L1Object.id) if not self.instance.contact_L1Object in [None, 0] else '0'
            self.fields['contact_L34Object'].initial = l34_name
            self.fields['L34Object_hidden'].initial = l34+';'+l2+';'+l1
    
    def save(self, force_insert=False, force_update=False, commit=True):
        data = self.cleaned_data.get('L34Object_hidden', None)
        m = super(UserProfileContactsForm, self).save(commit=False)
        if data is not None:
            (L34, L2, L1) = tuple([int(data.split(';')[i] if data.split(';')[i]<>'null' else 0) for i in range(0,3)])
            m.contact_L1Object = L1Object.objects.get(pk=L1) if L1!=0 else None
            m.contact_L2Object = L2Object.objects.get(pk=L2) if L2!=0 else None
            m.contact_L34Object = L34Object.objects.get(pk=L34) if L34!=0 else None
        if commit:
            m.save()
        return m
    
    class Media:
        js = ('js/ajax_geography.js', )
    
    class Meta:
        model = UserProfile
        fields = ('contact_email', 'contact_phone', 'contact_mobilephone', 'contact_icq', 'contact_gtalk', 'contact_jabber', 'contact_homepage', 'contact_L0Object')
    
class UserProfileSearchForm(forms.Form):
	

	first_name = forms.CharField(label=u'Имя', max_length=255)
	last_name = forms.CharField(label=u'Фамилия', max_length=255)
	birth_date = forms.DateField(label=u'Дата рождения', input_formats=DATE_INPUT_FORMATS)
	L34Object = forms.CharField(label=u'Город/поселок/деревня', required=False, widget=forms.TextInput(attrs={'autocomplete': 'off', 'class': 'id_L34Object'}))
	L34Object_hidden = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'autocomplete': 'off', 'class': 'id_L34Object_h'}))
	
	def clean_L34Object(self):
		data = self.cleaned_data.get('L34Object_hidden', None)
		if data is not None:
		    (L34, L2, L1) = tuple([int(data.split(';')[i] if data.split(';')[i]<>'null' else 0) for i in range(0,3)])
		    self.cleaned_data['L1Object'] = L1Object.objects.get(pk=L1) if L1!=0 else None
		    self.cleaned_data['L2Object'] = L2Object.objects.get(pk=L2) if L2!=0 else None
		    self.cleaned_data['L34Object'] = L34Object.objects.get(pk=L34) if L34!=0 else None
		    res = self.cleaned_data['L34Object']
		else:
			res = None
		return res
    
	class Media:
		js = ('js/ajax_geography.js', )    

class UserProfileAdminForm(forms.ModelForm):
    
    class Meta:
        model = UserProfile
        exclude = ('contact_L0Object', 'contact_L1Object', 'contact_L2Object', 'contact_L34Object', )